package com.cjq.allservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjq.allservice.entity.*;
import com.cjq.allservice.entity.vo.OrderQuery;
import com.cjq.allservice.entity.vo.UserQuery;
import com.cjq.allservice.service.GoodsService;
import com.cjq.allservice.service.OrderDetailService;
import com.cjq.allservice.service.OrdersService;
import com.cjq.allservice.service.StandingBookService;
import com.cjq.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjq
 * @since 2022-01-11
 */
@RestController
@RequestMapping("/allservice/orders")
@CrossOrigin
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    private final OrderDetailService orderDetailService;

    private final GoodsService goodsService;

    private final StandingBookService standingBookService;

    public OrdersController(OrderDetailService orderDetailService,GoodsService goodsService,StandingBookService standingBookService){
        this.orderDetailService=orderDetailService;
        this.goodsService=goodsService;
        this.standingBookService=standingBookService;
    }


    @ApiOperation("点击购买直接生成订单")
    @PostMapping("/addOrder")
    public R addOrder(@RequestBody OrderDetail orderDetail){
        Orders orders = new Orders();
        String userId = orderDetail.getUserId();
        orders.setOrderUserId(userId);
        Goods goods = goodsService.getById(userId);
        orders.setOrderTotalPrice(orderDetail.getNumber()*goods.getGoodsThirdPrice());
        boolean save = ordersService.save(orders);
        boolean save1 = orderDetailService.save(orderDetail);
        if (save==true){
            return R.succ().message("订单创建成功！");
        }else {
            return R.fail().message("订单创建失败！");
        }
    }

    @ApiOperation("删除/取消订单")
    @DeleteMapping("/deleteOrdersByUserId")
    public R deleteOrdersByUserId(@RequestParam String orderUserId){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("order_user_id",orderUserId);
        wrapper.eq("order_status",0);
        boolean b = ordersService.remove(wrapper);
        if (b==true){
            return R.succ().message("取消订单成功！");
        }else {
            return R.fail().message("取消订单失败！");
        }
    }

    @ApiOperation("修改订单状态:0-未完成，1-已支付，2-已发货，3-已签收，4-订单已完成")
    @PostMapping("/changeOrder")
    public R changeOrder(@RequestParam String orderId,@RequestParam Integer type){
        Orders orders = ordersService.getById(orderId);
        orders.setOrderStatus(type);

        if (type==1){//订单支付之后进行台账更新
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orders.getOrderId());
            List<OrderDetail> list = orderDetailService.list(wrapper);
            for (OrderDetail orderDetail:list){//进行台账记录表的统计
                Goods goods = goodsService.getById(orderDetail.getGoodsId());
                QueryWrapper<StandingBook> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("goods_id",orderDetail.getGoodsId());
                StandingBook one = standingBookService.getOne(wrapper1);
                if (one==null){
                    StandingBook standingBook = new StandingBook();
                    standingBook.setGoodsId(orderDetail.getGoodsId());

                    standingBook.setCost(goods.getGoodsFirstPrice()*goods.getGoodsSell());
                    standingBook.setIncome(goods.getGoodsThirdPrice()*goods.getGoodsSell());
                    standingBook.setSellNumber(goods.getGoodsNumber());
                    standingBookService.save(standingBook);
                }else {
                    one.setCost(goods.getGoodsFirstPrice()*goods.getGoodsSell());
                    one.setIncome(goods.getGoodsThirdPrice()*goods.getGoodsSell());
                    one.setSellNumber(goods.getGoodsNumber());
                    standingBookService.updateById(one);
                }

            }

            //standingBook.setGoodsId();
        }

        boolean b = ordersService.updateById(orders);
        if (b==true){
            return R.succ().message("订单支付成功！");
        }else{
            return R.fail().message("订单支付失败！");
        }

    }


    @ApiOperation("获取所有订单")
    @GetMapping("/getAllOrders")
    public R getAllOrders(){
        List<Orders> list = ordersService.list();
        return R.succ().data("ordersList",list);
    }

    @ApiOperation("根据用户id、订单id获取所有订单")
    @GetMapping("/getOrdersByUserId")
    public R getOrdersByUserId(@RequestParam String orderUserId,@RequestParam String orderId){
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",orderUserId);
        wrapper.eq("order_id",orderId);
        List list = orderDetailService.list(wrapper);
        return R.succ().data("ordersList",list);
    }


    @ApiOperation("条件查询用户带分页")
    //条件查询带分页
    @PostMapping ("pageOrderCondition/{current}/{limit}")
    public R pageUserCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) OrderQuery orderQuery){
        Page<Orders> page=new Page<>(current,limit);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();

        //多条件组合查询
        String id = orderQuery.getOrderId();
        String name = orderQuery.getOrderUserId();
        String orderAddressId=orderQuery.getOrderAddressId();
        if (!StringUtils.isEmpty(id)){
            wrapper.like("order_id",id);
        }
        if (!StringUtils.isEmpty(name)){
            wrapper.like("order_user_id",name);
        }
        if (!StringUtils.isEmpty(orderAddressId)){
            wrapper.like("order_status",orderAddressId);
        }
        wrapper.orderByDesc("update_time");

        ordersService.page(page,wrapper);
        long total=page.getTotal();
        System.out.println(total);
        List<Orders> records = page.getRecords();
        HashMap map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return R.succ().data(map);
    }



}

